/**
 * 运费设置
 */

import React, { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import SelectArea from './SelectArea';
import CopyFreightTemplate from './CopyFreightTemplate';
import { Form, Spin, message, InputNumber, Radio, Button, Popconfirm, Modal } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import { cloneDeep } from 'lodash';
import { getFreightDetail, saveFreight, updateFreight } from '../../service';

const templateArr = [
    {
        startWeight: "0", endWeight: "1"
    },
    {
        startWeight: "1.001", endWeight: "2"
    },
    {
        startWeight: "2.001", endWeight: "3"
    },
    {
        startWeight: "3.001", endWeight: "4"
    },
    {
        startWeight: "4.001", endWeight: "5"
    },
]; //活动价模板

export default ({ recordObj, obj, visible, handleOk, handleCancel }) => {

  const columns = [
    {
      title: '发货地区',
      dataIndex: 'areaName',
      key: 'areaName',
      render: (text, record, index) => {
        return (
          <div className="flex-column">
            <span>{text}</span>
            {record.scope == 2 && (
              <span className="common-color2" onClick={() => handleAddArea(record, index)}>
                添加发货区域
              </span>
            )}
          </div>
        );
      },
    },
    {
      title: '首重',
      children: [
        {
          title: '重量范围(kg)',
          dataIndex: 'startWeight',
          key: 'startWeight',
          width: 110,
          render: (text, record, index) => {
            return (
              <>
                <InputNumber style={{ width: 72 }} defaultValue={text} onBlur={e => handlePostAreasChange(e, index, 'startWeight')} min={0} step={0.001} />
              </>
            );
          },
        },
        {
          title: '金额(元)',
          dataIndex: 'startMoney',
          key: 'startMoney',
          width: 100,
          render: (text, record, index) => {
            return (
              <InputNumber style={{ width: 72 }} defaultValue={text} onBlur={e => handlePostAreasChange(e, index, 'startMoney')} min={0} step={0.01} />
            )
          }
        },
      ],
    },
    {
      title: '续重',
      children: [
        {
          title: '重量范围(kg)',
          dataIndex: 'addWeight',
          key: 'addWeight',
          width: 110,
          render: (text, record, index) => {
            return (
              <>
                <InputNumber style={{ width: 72 }} defaultValue={text} onBlur={e => handlePostAreasChange(e, index, 'addWeight')} min={0.001} step={0.001} />
              </>
            );
          },
        },
        {
          title: '金额(元)',
          dataIndex: 'addMoney',
          key: 'addMoney',
          width: 100,
          render: (text, record, index) => {
            return (
              <InputNumber style={{ width: 72 }} defaultValue={text} onBlur={e => handlePostAreasChange(e, index, 'addMoney')}  min={0} step={0.01} />
            )
          }
        },
      ],
    },
    {
      title: '活动价',
      children: [
        {
          title: '重量范围(kg)',
          dataIndex: 'activitys',
          key: 'activitys',
          width: 200,
          //{ startWeight, endWeight, money }
          render: (text, record, index) => {
            return {
              children: text ? (
                <>
                  {text.map((v, index1) => (
                    <div
                      className="flex"
                      key={index1}
                      style={{ alignItems: 'center', marginBottom: '8px' }}
                    >
                      <div>
                        <InputNumber
                          defaultValue={v.startWeight}
                          onBlur={(e) => handlePostActivitysChange(e, index, index1, 'startWeight')}
                          style={{ width: 72 }}
                         
                          min={0}
                          step={0.001}
                        />
                        <span style={{ width: 72, margin: '0 4px' }}>
                          ~
                        </span>
                        <InputNumber
                          defaultValue={v.endWeight}
                          onBlur={(e) => handlePostActivitysChange(e, index, index1, 'endWeight')}
                          style={{ width: 72 }}
                         
                          min={0}
                          step={0.001}
                        />
                      </div>
                      <InputNumber
                        defaultValue={v.money}
                        onBlur={(e) => handlePostActivitysChange(e, index, index1, 'money')}
                        style={{ width: 72, marginLeft: '36px' }}
                       
                        min={0}
                        step={0.01}
                      />
                      <CloseOutlined
                        onClick={() => handleSetActivityPrice(1, index, index1)}
                        style={{ cursor: 'pointer', marginLeft: '4px' }}
                      />
                    </div>
                  ))}
                  <span className="common-color2" onClick={() => handleSetActivityPrice(2, index)}>
                    添加活动价
                  </span>
                  <span style={{marginLeft: '10px'}} className="common-color2" onClick={() => handleSetActivityPriceTemplate(index)}>
                    使用活动价模板
                  </span>
                </>
              ) : (
                <span className="common-color2" onClick={() => handleSetActivityPrice(2, index)}>
                  添加活动价
                </span>
              ),
              props: {
                colSpan: 2,
              },
            };
          },
        },
        {
          title: '金额(元)',
          dataIndex: 'activitys',
          key: 'activitys1',
          width: 120,
          render: () => {
            return {
              children: null,
              props: {
                colSpan: 0,
              },
            };
          },
        },
      ],
    },
    {
      title: '计抛系数',
      dataIndex: 'bubble',
      key: 'bubble',
      width: 100,
      render: (text, record, index) => {
        return (
          <>
            <InputNumber
              style={{ width: 72 }}
              defaultValue={text}
              onBlur={(e) => handlePostAreasChange(e, index, 'bubble')}
             
              min={0}
              step={0.01}
            />
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'scope',
      key: 'scope',
      width: 80,
      render: (text, record, index) => {
        if (text == 1) {
          return '-';
        }
        return (
          <Popconfirm
            title="确定要删除该运费配置吗?"
            onConfirm={() => handleDeleteFreight(index)}
            okText="确定"
            cancelText="取消"
          >
            <span className="common-color2">删除</span>
          </Popconfirm>
        );
      },
    },
  ];

  const [data, setData] = useState({});
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [key, setKey] = useState(1);
  const [item, setItem] = useState({});
  const [index, setIndex] = useState(undefined);
  const [areaVisible, setAreaVisible] = useState(false);
  const [copyVisible, setCopyVisible] = useState(false); //复制运费模板弹窗
  const [ selectId, setSelectId ] = useState([]);
  const { downStart, downEnd, postAreas = [], upStart, upEnd, method } = data;
  const { id } = obj;

  if (postAreas.length == 0) {
    const obj = {
      areaName: '默认全国',
      activitys: [],
      scope: 1,
      newSelectId: [],
    };
    postAreas.push(obj);
  }

  useEffect(() => {
    if (visible) {
      getFreightData();
      form.resetFields();
    }
  }, [visible]);

  useEffect(() => {
    if (visible) {
      form.resetFields();
    }
  }, [key]);

  //获取运费详情
  const getFreightData = async () => {
    setLoading(true);
    const res = await getFreightDetail({
      expressNetworkId: id
    })
    if(res.success) {
      setData(res.data);
      setKey(key + 1);
      setLoading(false);
    } else {
      setLoading(false);
    }
  }

    //获取运费详情(复制)
    const getFreightCopyData = async (id) => {
        setLoading(true);
        const res = await getFreightDetail({
          expressNetworkId: id,
        });
        const { id: newId } = data;
        if (res.success) {
          const obj = res.data;
          if (newId) {
            obj.id = newId;
          } else {
            delete obj.id;
          }
          setData(obj);
          setKey(key + 1);
          setLoading(false);
        } else {
          setLoading(false);
        }
      };

  //提交修改,校验数据
  const handleSubmit = () => {
    for (let i in postAreas) {
      if (!postAreas[i].areaName) {
        message.warning('发货区域未设置');
        return;
      }
      if (
        postAreas[i].startWeight &&
        postAreas[i].startMoney &&
        postAreas[i].addWeight &&
        postAreas[i].addMoney
      ) {
        //校验通过
        continue;
      } else {
        message.warning('首重和续重以及金额必填且大于零');
        return;
      }
    }

    const arr = cloneDeep(postAreas);
    for (let i in arr) {
      const list = [];
      const arr1 = arr[i].newSelectId;
      for (let k in arr1) {
        const arr2 = arr1[k].childs;
        for (let j in arr2) {
          const arr3 = arr2[j].childs;
          for (let z in arr3) {
            list.push(arr3[z].id);
          }
        }
      }
      arr[i].areaIds = list;
      delete arr[i].newSelectId;
    }
    setFreight(arr);
  };

  //提交运费修改
  const setFreight = async (arr) => {
    setLoading(true);
    let res;
    const val = form.getFieldValue('method');
    if (data.id) {
      res = await updateFreight({
        ...data,
        method: val,
        postAreas: arr,
        expressNetworkId: id,
      });
    } else {
      res = await saveFreight({
        ...data,
        method: val,
        postAreas: arr,
        expressNetworkId: id,
      });
    }
    setLoading(false);
    if (res.success) {
      message.success('设置成功！');
      handleOk();
      handleCancel();
    }
  };

  //添加发货区域弹框
  const handleAddArea = async (record, index) => {
    let arr = [];
    const list = [];
    for(let i in postAreas) {
      if(i == index) { continue };
      arr = [ ...arr, ...postAreas[i].newSelectId ];
    }
    for (let i in arr) {
      const arr1 = arr[i].childs;
      for (let j in arr1) {
        const arr2 = arr1[j].childs;
        for (let z in arr2) {
          if(list.includes(arr2[z].id)) {
            continue
          }
          list.push(arr2[z].id);
        }
      }
    }
    setSelectId(list.join());
    setIndex(index);
    setItem(record);
    setAreaVisible(true);
  };

  //获取已选中区域
  // const getPreViewData = async (record) => {
  //   setLoading(true);
  //   const res = await getSelectArea({
  //     postAreaId: record.id,
  //   });
  //   setLoading(false);
  //   if (res.success) {
  //     record.newSelectId = res.data;
  //     setItem(record);
  //     setAreaVisible(true);
  //   }
  // };

  //删除运费配置
  const handleDeleteFreight = (index) => {
    const arr = cloneDeep(postAreas);
    arr.splice(index, 1);
    const obj = cloneDeep(data);
    obj.postAreas = arr;
    setData(obj);
    setKey(key+1);
  }

  const onCancel = () => {
    handleCancel();
    setData({});
  };

  const onOk = () => {
    if(loading) {
      return false;
    }
    form.validateFields().then((val) => {
      handleSubmit();
    });
  };

  //更改运费列表设置
  const handlePostAreasChange = (e, index, label) => {
    const val = e.target.value;
    postAreas[index][label] = val;
    data.postAreas = postAreas;
  }

  //更改活动价设置
  const handlePostActivitysChange = (e, index, index1, label) => {
    const val = e.target.value;
    postAreas[index].activitys[index1][label] = val;
    data.postAreas = postAreas;
  } 

  //删除/新增 活动价
  const handleSetActivityPrice = (type, index, index1 = null) => {
    const arr = cloneDeep(postAreas);
    if (type == 1) {
      //删除
      arr[index].activitys.splice(index1, 1);
    } else {
      if (arr[index].activitys) {
        arr[index].activitys.push({});
      } else {
        arr[index].activitys = [];
        arr[index].activitys.push({});
      }
    }
    const obj = cloneDeep(data);
    obj.postAreas = arr;
    setData(obj);
    setKey(key+1);
  } 

  //使用活动价模板
  const handleSetActivityPriceTemplate = (index) => {
    const arr = cloneDeep(postAreas);
    if (arr[index].activitys) {
        arr[index].activitys.unshift(...templateArr);
      } else {
        arr[index].activitys = [];
        arr[index].activitys.unshift(...templateArr);
      }
     console.log('handleSetActivityPriceTemplate', arr);
    const obj = cloneDeep(data);
    obj.postAreas = arr;
    setData(obj);
    setKey(key+1);
  }
  
  //更改运费设置
  const handleDataChange = (e, label) => {
    const val = e.target.value;
    data[label] = val;
  }

  //点击新增运费配置
  const handleAddFreightConfig = () => {
    const obj = {
      activitys: [],
      scope: 2,
      newSelectId: [],
    };
    const arr = cloneDeep(postAreas);
    arr.push(obj);
    const obj1 = cloneDeep(data);
    obj1.postAreas = arr;
    setData(obj1);
    setKey(key+1);
  }

  const TableProps = {
    data: postAreas,
    columns,
    title: () => <> <Button style={{ marginRight: '8px' }} onClick={handleAddFreightConfig}>新增运费配置</Button> <Button onClick={() => {setCopyVisible(true)}}>复制其他快递模板</Button> </>
  };

  const SelectAreaProps = {
    visible: areaVisible,
    item: item,
    id: selectId,
    handleOk(val) {
      const obj = cloneDeep(data);
      let str = '';
      val.map((v) => (str += `,${v.name}`));
      postAreas[index].newSelectId = val;
      postAreas[index].areaName = str.replace(',', '');
      obj.postAreas = postAreas;
      setData(obj);
    },
    handleCancel() {
      setAreaVisible(false);
    },
  };

  //复制运费模板
  const CopyFreightTemplateProps = {
    visible: copyVisible,
    handleCancel() {
        setCopyVisible(false);
    },
    handleOk(val) {
        setCopyVisible(false);
        getFreightCopyData(val);
    }
  }

  return (
    <CommonModal className='freight' title={`修改运费（${recordObj?.expressName}-${obj?.networkName}）`} visible={visible} width="1200px" onOk={onOk} onCancel={onCancel}>
      <Spin spinning={loading}>
        <Form
          layout="horizontal"
          name='set-freight'
          form={form}
          initialValues={{
            method,
          }}
        >
          <Form.Item
            name="method"
            label="计费方式"
            rules={[{ required: true, message: '请选择计费方式' }]}
          >
            <Radio.Group>
              <Radio value={1}>按重量计算</Radio>
              <Radio value={2}>按订单计算</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="称重取舍" key={key}>
            <div>
              <div style={{ marginBottom: '8px' }}>
                <InputNumber
                  defaultValue={downStart}
                  onBlur={(e) => handleDataChange(e, 'downStart')}
                  min={0}
                  step={0.001}
                />
                <span style={{ margin: '0 4px' }}>~</span>
                <InputNumber
                  defaultValue={downEnd}
                  onBlur={(e) => handleDataChange(e, 'downEnd')}
                  min={0}
                  step={0.001}
                />
                <span style={{ marginLeft: '8px' }}>向下取整计算运费</span>
              </div>
              <div>
                <InputNumber
                  defaultValue={upStart}
                  onBlur={(e) => handleDataChange(e, 'upStart')}
                  min={0}
                  step={0.001}
                />
                <span style={{ margin: '0 4px' }}>~</span>
                <InputNumber
                  defaultValue={upEnd}
                  onBlur={(e) => handleDataChange(e, 'upEnd')}
                  min={0}
                  step={0.001}
                />
                <span style={{ marginLeft: '8px' }}>向上取整计算运费</span>
              </div>
            </div>
          </Form.Item>
        </Form>
        <CommonTable key={key} {...TableProps} />
      </Spin>
      <SelectArea {...SelectAreaProps} />
      {
        copyVisible && (<CopyFreightTemplate {...CopyFreightTemplateProps} />)
      }
    </CommonModal>
  );
};
